﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Site_CustomerCheckout2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
		if (!IsPostBack)
		{
			this.Form.Action = "Site/CustomerCheckout2.aspx";
			EF_CustomerProperty customer = new EF_CustomerProperty();
			customerName.Text = Session["CustomerName"].ToString();
			customerPhone.Text = Session["CustomerPhone"].ToString();
			customerEmail.Text = Session["CustomerEmail"].ToString();
			shippingAddress.Text = Session["ShippingAddress"].ToString();

			cartView.DataSource = ShoppingCartAccess.GetItems();
			cartView.DataBind();

			decimal amount = ShoppingCartAccess.GetTotalAmount();
			totalAmountLabel.Text = String.Format("{0:c}", amount);
		}
    }

	protected void nextCompleteCheckout_Click(object sender, EventArgs e)
	{
		// Get the total amount
		decimal amount = ShoppingCartAccess.GetTotalAmount();
		// Get customer information
		EF_CustomerProperty customer = new EF_CustomerProperty();
		customer.CustomerName = customerName.Text;
		customer.CustomerPhone = customerPhone.Text;
		customer.CustomerEmail = customerEmail.Text;
		customer.ShippingAddress = shippingAddress.Text;
		​​​// Create email body
		DataTable dt = ShoppingCartAccess.GetItems();
		string body = "<!DOCTYPE HTML><html lang=\"km\"><head><meta charset=\"UTF-8\"></head><body><table border=\"1\" cellpadding=\"5\" cellspacing=\"0\" style=\"border-collapse: collapse;\"><thead><tr><th align=\"left\">ល.រ</th><th align=\"left\">ឈ្មោះទំនិញ</th><th align=\"left\">តម្លៃរាយ</th><th align=\"left\">ចំនួន</th><th align=\"left\">សរុប</th></tr></thead><tbody>";
		foreach(DataRow dr in dt.Rows)
		{
			string tt = dr["Name"].ToString();
			body += "<tr>"
				+ "<td>" + dr["Name"].ToString()+"</td>"
				+ "<td>" + String.Format("{0:c}", dr["Price"]).ToString() +"</td>"
				+ "<td>" + dr["Quantity"].ToString() +"</td>"
				+ "<td>" + String.Format("{0:c}", dr["Subtotal"]).ToString() +"</td>"
				+"</tr>";

		}

		body += "<tr><td colspan=\"3\" align=\"right\">សរុបរួម</td><td>" + String.Format("{0:c}", amount).ToString() +"</td></tr>";
		body += "</tbody></table></body>";

		// Create the order and store the order ID
		ShoppingCartAccess.CreateOrder(customer);
		if (ElegantFoodConfiguration.EnableSendInvoice)
		{
			string subject = "Elegant Food - Order invoice";
			string to = customerEmail.Text;
			Utilities.SendMail(ElegantFoodConfiguration.MailFrom, to, subject, body);
		}
		Response.Redirect("CustomerCheckoutComplete.aspx");
	}
}